
package uestc.bitman.edxapp.courselist;

import uestc.bitman.edxapp.EdxApp;
import uestc.bitman.edxapp.EdxStudentUser;
import uestc.bitman.edxapp.R;
import uestc.bitman.edxapp.chapter.CourseChaptersFragment;
import uestc.bitman.edxapp.mainui.EdxAppFragment;
import uestc.bitman.edxapp.mainui.MainActivity;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;

import java.util.List;

/**
 * @category CourseFragment of course list
 */
@SuppressLint("CommitTransaction")
public class MyCourseListFragment extends EdxAppFragment implements
        SwipeRefreshLayout.OnRefreshListener {

    /**
     * Progress dialog of loading
     */
    private ProgressDialog mProgressDlg;

    private ListView mCourseListView;

    private MyCourseListAdapter mCourseAdapter;

    private Context mContext;

    private SwipeRefreshLayout mSwipeRefreshLayout;

    private CourseChaptersFragment mChapterFragment;

    /**
     * @category Constructor
     */
    public MyCourseListFragment() {

    }

    /**
     * @category onCreate
     */
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = getActivity();
        mCourseAdapter = new MyCourseListAdapter(mContext);
        mChapterFragment = new CourseChaptersFragment();
        initCourseList();
    }

    /**
     * @category Initialize UI here
     */
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);

        // when switch to this page,update the title and enable the press again
        // to exit(because this page is at home)
        
        setHasOptionsMenu(true);

        View view = initLayout(inflater, container, savedInstanceState);

        // refresh the course list
        onRefresh();

        return view;
    }

    private View initLayout(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.course_fragment, container, false);

        mCourseListView = (ListView) view.findViewById(R.id.list_course);
        mCourseListView.setOnItemClickListener(new OnCourseSelectedListener());
        mCourseListView.setAdapter(mCourseAdapter);

        mSwipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipe_container);
        mSwipeRefreshLayout.setOnRefreshListener(this);
        mSwipeRefreshLayout.setColorScheme(android.R.color.holo_blue_bright,
                android.R.color.holo_green_light, android.R.color.holo_orange_light,
                android.R.color.holo_red_light);

        return view;
    }

    /**
     * @category Initialize data such as course list
     */
    private void initCourseList() {

        CourseListAsyncTask courseListAsyncTask = new CourseListAsyncTask();
        courseListAsyncTask.execute(EdxApp.getEdxAppUser());
        mProgressDlg = ProgressDialog.show(mContext, getString(R.string.title_processing),
                getString(R.string.label_content_processing));
    }

    /**
     * @category Refresh while the user swipe down at the list,we can also call
     *           this to refresh.
     */
    @Override
    public void onRefresh() {
        mSwipeRefreshLayout.setRefreshing(true);
        CourseListAsyncTask courseListAsyncTask = new CourseListAsyncTask();
        courseListAsyncTask.execute(EdxApp.getEdxAppUser());
    }

    /**
     * @author hackeris
     * @category Listener for course list clicked
     */
    class OnCourseSelectedListener implements OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Course course = mCourseAdapter.getItem(position);
            mChapterFragment.setCourse(course);
            startFragment(mChapterFragment, R.id.content_frame, "chapters", true);
        }
    }

    /**
     * @category AsyncTask for loading course list. Needs an EdxStudentUser
     *           instance to get course list.
     */
    class CourseListAsyncTask extends AsyncTask<EdxStudentUser, Void, List<Course>> {
        @Override
        /**
         *  Call studentUser.getCourseList to get course list
         */
        protected List<Course> doInBackground(EdxStudentUser... params) {
            EdxStudentUser studentUser = params[0];
            return studentUser.getCourseList();
        }

        /**
         * Here we can update the course list view
         */
        protected void onPostExecute(List<Course> courseList) {
            mProgressDlg.dismiss();
            mSwipeRefreshLayout.setRefreshing(false);
            /**
             * If the courseList is null which means failed,we show the Toast
             */
            if (courseList == null) {
                Toast.makeText(mContext, getString(R.string.label_get_courselist_failed),
                        Toast.LENGTH_SHORT).show();
                return;
            }

            mCourseAdapter.reloadCourseList(courseList);
            mCourseAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_exit:
                getActivity().finish();
                return true;
        }
        return false;
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.menu_course_list, menu);
    }
}
